package com.lsm.czxxgl_system.Interceptor;

import com.lsm.czxxgl_system.constant.UserConstant;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: PageIntercepter
 * Package: com.lsm.czxxgl_system.Interceptor
 * Description:
 *
 * @Author lsm
 * @Create 2024/6/26 23:31
 * @Version 1.0
 */
@Component
public class PageInterceptor implements HandlerInterceptor {
    /**
     * 拦截未登录的用户发起的请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //判断是否存在用户的登录态
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            //用户未登录，拦截请求状态码
            //在请求域中设置错误信息
            request.setAttribute("error_msg","请先登录");
            //请求转发至登录页面
            request.getRequestDispatcher("/").forward(request,response);
            return false;
        }
        return true;
    }
}
